from util.DbUtils import Tool
from wrapper.FunctionWrapper import log

t = Tool()


class Function(object):
    # 注册成功添加用户信息
    def reg_change(self, uname, upwd):
        t.update("insert into userinfo values('{}','{}',0)".format(uname, upwd))

    # 修改余额
    @log
    def money_change(self, index, money):
        user_list = t.select("select * from userinfo")
        uinfo = user_list[index]
        uname = uinfo[0]
        balance = uinfo[2]
        balance += money
        t.update("update userinfo set balance = {} where uname = '{}' ".format(balance, uname))

    # 输入用户名
    def input_uname(self):
        uname = input("请输入用户名:")
        if self.check_uname(uname) >= 0:
            print("用户名已存在")
            uname = self.input_uname()
        return uname

    # 验证用户名是否存在
    def check_uname(self, uname):
        user_list = t.select("select * from userinfo")
        for i in range(len(user_list)):
            if user_list[i][0] == uname:
                return i
        return -1

    # 检查余额是否足够
    def check_money(self, money, index):
        user_list = t.select("select * from userinfo")
        if user_list[index][2] < money:
            return 0
        else:
            return 1
